<template>
    <div class="project-detail-container">
        <UserNav/>
        <!-- 只有当 project.value 存在时才渲染 -->
        <el-card class="project-header" v-if="project">
                <div>
                    <div style="display: flex; align-items: center">
                        <img src="@/assets/icon_svg/项目.svg" alt="项目" style="width: 30px; height: 30px">
                        <el-button link style="font-size: 16px"><h2 style="margin-left: 20px">{{project.user?.username}}</h2></el-button>
                        <h2> / {{project?.projectName}}</h2>
                    </div>
                    <div style="display: flex; justify-content: space-between">
                        <span style="display: flex;"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 22px; height: 22px; font-size: 16px; margin-right: 7px">{{project?.views}}</span>
                        <span style="display:flex;">发布于{{ formatDate(project?.createdAt) }}</span>
                    </div>
                </div>
        </el-card>

        <el-tabs style=" margin-left: 40px; background-color: white" v-model="activeTab" type="border-card">
            <el-tab-pane label="项目文件" name="files">
                <div class="flex">
                    <div class="file-browser">
                        <div style="display: flex; justify-content: space-between; right: 20px; top: 70px" v-if="!isManagerAuth?.value">
                            <div style="display: flex; gap: 20px">
                                <el-upload
                                    action="#"
                                    :http-request="uploadFile"
                                    :data="{ projectId: route.params.id }"
                                    :show-file-list="false"
                                    accept="*">
                                    <el-button type="primary">上传文件</el-button>
                                </el-upload>
                                <el-button type="primary" @click="createFolder">创建文件夹</el-button>
                                <!--<el-button type="info" @click="downloadProject">克隆/下载</el-button>-->
                            </div>
                        </div>
                        <!--复选框 show-checkbox-->
                        <div style="margin-top: 20px; min-height: 300px">
                            <el-tree
                                style="font-size: 15px"
                                :data="filteredFileTree"
                                :props="treeProps"
                                node-key="id"
                                accordion
                                :default-expanded-keys="[]"
                                :default-checked-keys="[]"
                                @node-click="handleNodeClick"
                                @node-contextmenu="handleContextMenu">
                                <template #default="{ node, data }">
                                    <span>
                                      <el-icon v-if="data.directory"><Folder /></el-icon>
                                      <el-icon v-else><Document /></el-icon>
                                      {{ data.label }}
                                    </span>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                </div>
                <!-- 菜单右击 -->
                <el-popover
                    placement="right"
                    title="操作菜单"
                    trigger="manual"
                    :visible.sync="contextMenuVisible"
                    :popper-options="{ offset: 10 }"
                >
                    <template #default>
                        <el-button @click="downloadFile(contextMenuNode.value.data)">下载</el-button>
                        <el-button @click="previewFile(contextMenuNode.value.data)">预览</el-button>
                        <el-button @click="renameFile(contextMenuNode.value.data)">重命名</el-button>
                        <el-button @click="deleteFile(contextMenuNode.value.data)">删除</el-button>
                    </template>
                    <template #reference>
                        <div ref="contextMenuRef"></div>
                    </template>
                </el-popover>
            </el-tab-pane>
            <el-tab-pane label="项目成员" name="members">
                <el-card>
                    <div class="flex justify-between mb-4">
                        <h3 class="font-bold">项目成员管理</h3>
                        <el-button type="primary" @click="handleAddMember" v-if="isManagerAuth">添加成员</el-button>
                    </div>

                    <el-table :data="members" stripe>
                        <el-table-column prop="username" label="用户名"></el-table-column>
                        <el-table-column prop="roleName" label="角色"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="small" @click="handleEditMember(scope.row)">编辑</el-button>
                                <el-button size="small" type="danger" @click="handleRemoveMember(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-tab-pane>
            <el-tab-pane label="项目管理" name="manager" v-if="isManagerAuth">
                <el-card>
                    <div class="flex justify-between mb-4">
                        <el-button type="primary" @click="handleDeleteProject">注销项目</el-button>
                        <el-button type="primary" @click="handleEditProject">修改项目设置</el-button>
                    </div>
                </el-card>
            </el-tab-pane>
        </el-tabs>
    </div>

    <!-- 项目详情区域开始 -->
    <div class="content-user">
        <router-link :to="`/personalhome/${project.userId}`">
            <!-- 用户头像及用户名 -->
            <div style="display: flex; align-items: center; justify-content: center; margin: 20px 0 20px 0; gap: 20px">
                <el-avatar :src="project.user.profile_photo_path" shape="circle" :size="45"></el-avatar>
                <strong style="font-size: 17px">{{ project.user.username }}</strong>
            </div>
        </router-link>
    <!--        &lt;!&ndash; 其他信息 &ndash;&gt;-->
    <!--        <div style="display: flex; align-items: center; justify-content: center; gap: 50px">-->
    <!--            &lt;!&ndash; 文章数 &ndash;&gt;-->
    <!--            <div>-->
    <!--                <p style="text-align: center">{{12}}</p>-->
    <!--                <strong style="font-weight: 500; font-size: 15px">内容数</strong>-->
    <!--            </div>-->
    <!--            &lt;!&ndash; 项目数 &ndash;&gt;-->
    <!--            <div>-->
    <!--                <p style="text-align: center">3</p>-->
    <!--                <strong style="font-weight: 500; font-size: 15px">项目数</strong>-->
    <!--            </div>-->
    <!--        </div>-->
            <!-- 关注私信按钮 -->
            <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 10px; border-bottom: 1px #cccbc8 solid;">
                <el-button type="primary" style="width: 130px ; margin: 10px">关注</el-button>
                <el-button style="width: 130px; margin: 10px" @click="privateMessage">私信</el-button>
            </div>
        <!-- 项目信息区域 -->
        <div >
            <!-- 简介区域 -->
            <div style="margin: 10px; font-weight: 500">
                <span style="font-size: 15px; font-weight: 500">项目简介:</span>
                <p class="text-gray-500 mt-1">{{project?.projectName}}: {{ project?.description || '暂无描述' }}</p>
            </div>
            <!-- 其他区域 -->
            <div style="max-height: 350px; min-height: 200px; background-color: #fffefb; margin: 10px">
                    <!--项目分类-->
                    <div><span>项目分类：
                        <el-tag v-if="project.category?.categoryName" type="info">{{ project.category?.categoryName }}</el-tag>
                        <el-tag v-else type="info">其他</el-tag>
                    </span></div>
                    <!--我的标签区域开始-->
                    <div style="margin-top: 20px">
                        <p style="">项目标签：</p>
                        <div style="">
                            <span v-if="project.tags"><el-tag v-for="tag in project.tags.split(',')" :key="tag" type="success" style="margin-right: 10px">{{ tag }}</el-tag></span>
                            <span v-else>您暂未选择标签！</span>
                            <el-button @click="dialogVisible = true" style="margin-left: 20px"><el-icon><Plus /></el-icon>&nbsp;&nbsp;添加标签</el-button>
                        </div>
                    </div>
                    <!--我的标签区域结束-->

                    <!-- 添加标签弹框开始 -->
                    <el-dialog title="添加感兴趣的标签" v-model="dialogVisible" width="600px" destroy-on-close align-center>
                        <p>选择现有标签添加（最多添加10个）</p>
                        <!-- 现有标签列表 -->
                        <div class="existing-tags">
                            <h4>热门标签</h4>
                            <el-tag
                                v-for="tag in hotTags"
                                :key="tag.tagId"
                                :type="tag.isSelected ? 'success' : ''"
                                @click="toggleTagSelection(tag)"
                                style="margin-right: 8px; margin-top: 8px; cursor: pointer">
                                {{ tag.tagName }}
                            </el-tag>
                        </div>
                        <!-- 已选标签预览 -->
                        <div v-if="selectedTags.length > 0" class="selected-preview">
                            <h4>已选标签</h4>
                            <el-tag
                                v-for="tag in selectedTags"
                                :key="tag.tagId || tag.tempId"
                                type="success"
                                closable
                                @close="handleSelectedRemove(tag)"
                            >
                                {{ tag.tagName }}
                            </el-tag>
                        </div>
                        <template #footer>
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitTags">确认添加</el-button>
                        </template>
                    </el-dialog>
                    <!-- 添加标签弹框结束 -->
                <span class="publish-time">{{ project.created_at.split(' ')[0] }}</span>
            </div>
        </div>
    </div>
    <!-- 项目信息区域结束 -->
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";
import UserNav from "@/components/UserNav.vue";
import {Document, Folder, Plus} from "@element-plus/icons-vue";

// 解析用户信息（确保初始化）
const loginUser = localStorage.getItem('code_user');
const user = loginUser ? JSON.parse(loginUser) : null;

const route = useRoute()
const router = useRouter()

// 状态管理（全部使用 ref）
const project = reactive({
    userId: '',
    projectName: '',
    description: "",
    path: "",
    property: "",
    visibility: "",
    created_at: "",
    views: 0,
    user: {
        username: "",
        profile_photo_path: "",
    }
}) // 初始化为空对象
const activeTab = ref('files')
const members = ref([])
const fileTree = ref([])
const isManagerAuth = ref(false) // 改为 ref
const selectedFile = ref(null)
const filteredFileTree = ref([])
const contextMenuVisible = ref(false)
const contextMenuNode = ref(null)
const contextMenuRef = ref()
// 初始化
onMounted(() => {
    fetchProjectDetails()  // 加载项目详情
    buildFileTree()  // 加载文件树
    updateViews(contentData);    // 增加浏览量
})
// 内容数据
const contentData = {
    userId: user?.user_id || null,  // 当前浏览内容的用户
    targetId: route.params.id,
    targetType: 'PROJECT'
}
// 获取项目详情（使用 async/await 更清晰）
const fetchProjectDetails = async () => {
    try {
        const res = await request.get(`/api/projects/getProjectById/${route.params.id}`)
        if (res.code === '200') {
            Object.assign(project, res.data);

            // 安全地检查 user 和 project.userId
            if (user && project.userId) {
                isManagerAuth.value = String(user.user_id) === String(project.userId)
            }
        } else {
            ElMessage.error("无法获取项目详情")
            await router.push({name: 'ProjectList'})
        }
    } catch (error) {
        ElMessage.error(error.message || '获取项目详情失败')
    }
}

// 树配置
const treeProps = {
    children: 'children',
    label: 'label'
}
// 创建文件夹
const createFolder = async () => {
    try {
        const folderName = await ElMessageBox.prompt('请输入文件夹名称', '创建文件夹', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        });
        if (folderName.value) {
            const res = await request.post('/api/projects/createFolder', {
                projectId: route.params.id,
                folderName: folderName.value,
            });
            if (res.code === '200') {
                ElMessage.success('文件夹创建成功');
                await buildFileTree();
            } else {
                ElMessage.error(res.msg || '文件夹创建失败');
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '创建文件夹失败');
        }
    }
};

// 构建文件树
const buildFileTree = async () => {
    try {
        const res = await request.get(`/api/projects/getFileTree/${route.params.id}`);
        if (res.code === '200') {
            fileTree.value = res.data.children;
            filteredFileTree.value = fileTree.value;
        } else {
            ElMessage.error('获取文件树失败');
        }
    } catch (error) {
        ElMessage.error(error.message || '获取文件树失败');
    }
}

// 上传文件
const uploadFile = async (params) => {
    try {
        const formData = new FormData();
        formData.append('file', params.file);
        formData.append('projectId', params.data.projectId);

        const res = await fetch(`http://localhost:8000/api/projects/uploadFile/${params.data.projectId}`, {  // fetch API 确保请求类型为多部份请求multipart/form-data; boundary=----WebKitFormBoundarylqI2UwWlakXjRvhE
            method: 'POST',
            body: formData
        });
        if (res.status === 200) {
            ElMessage.success('文件上传成功');
            await buildFileTree();
        } else {
            ElMessage.error(res.msg || '文件上传失败');
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试');
    }
};
// 文件点击
const handleNodeClick = (data) => {
    if (!data.isDirectory) {
        selectedFile.value = data;
    }
}
// 鼠标右击文件时方法
const handleContextMenu = (node, data, event) => {
    event.preventDefault();
    contextMenuNode.value = node;
    contextMenuVisible.value = true;
    contextMenuRef.value.style.left = `${event.clientX}px`;
    contextMenuRef.value.style.top = `${event.clientY}px`;
};
// 右键菜单功能
// 判断是否为二进制文件
const BINARY_FILE_EXTENSIONS = ['.jpg', '.png', '.pdf', '.gif', '.docx', '.xlsx', '.pptx'];
const isBinaryFile = (fileName) => {
    if (!fileName || typeof fileName !== 'string') return false;
    const extension = fileName.slice((fileName.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
    return BINARY_FILE_EXTENSIONS.includes(`.${extension}`);
};
// 获取预览链接
const getPreviewUrl = (file) => {
    return `/api/projects/previewFile/${encodeURIComponent(file.id)}`;
};
// 下载文件
const downloadFile = (file) => {
    window.open(`/api/projects/downloadFile/${encodeURIComponent(file.id)}`, '_blank');
};
// 预览文件
const previewFile = (file) => {
    if (isBinaryFile(file.label)) {
        downloadFile(file);
    } else {
        selectedFile.value = file;
    }
};
// 重命名文件
const renameFile = async (file) => {
    try {
        const newName = await ElMessageBox.prompt('请输入新的文件名', '重命名文件', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: file.label,
        });
        if (newName.value) {
            const res = await request.post('/api/projects/renameFile', {
                fileId: file.id,
                newName: newName.value,
            });
            if (res.code === '200') {
                ElMessage.success('文件重命名成功');
                buildFileTree();
            } else {
                ElMessage.error(res.msg || '文件重命名失败');
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '文件重命名失败');
        }
    }
};
// 删除文件
const deleteFile = async (file) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除文件 "${file.label}" 吗？此操作不可撤销。`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        const res = await request.post('/api/projects/deleteFile', {
            fileId: file.id,
        });
        if (res.code === '200') {
            ElMessage.success('文件删除成功');
            buildFileTree();
        } else {
            ElMessage.error(res.msg || '文件删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '文件删除失败');
        }
    }
};





// 页面事件处理 ： 修改项目
const handleEditProject = () => {

}

const handleDeleteProject = async () => {
    try {  // 提示加输入密码验证
        await ElMessageBox.confirm(
            `确定要删除项目 "${project.projectName}" 吗？此操作不可撤销。`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        request.get('/api/projects/deleteProject/' + route.params.id).then(res => {
            if (res.code === '200') {
                ElMessage.error("删除成功")
                router.push({name: 'ProjectList'})
            } else {
                ElMessage.error("删除项目失败")
            }
        })
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除项目失败')
        }
    }
}



// 获取项目成员
const fetchMembers = async () => {

}

const handleAddMember = () => {
    // 打开添加成员模态框
}

const handleEditMember = (member) => {
    // 打开编辑成员模态框
}

const handleRemoveMember = async (member) => {
    try {
        await ElMessageBox.confirm(
            `确定要移除成员 "${member.username}" 吗？`,
            '确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // request.post()
        ElMessage.success('成员移除成功')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '移除成员失败')
        }
    }
}




// 添加标签
const dialogVisible = ref(false);  // 状态管理
const hotTags = ref([]); // 从后端获取的热门标签
const selectedTags = ref([]); // 已选标签（包含现有标签和自定义标签）

// 初始化：打开对话框时加载热门标签
watch(() => dialogVisible.value, (newVal) => {
    if (newVal) {
        fetchHotTags();
        resetState(); // 重置选择状态
    }
});

// 获取热门标签
const fetchHotTags = async () => {
    try {
        const res = await request.get('/api/cata/selectTagAll');
        if (res.code === '200') {
            hotTags.value = res.data.map(tag => ({
                ...tag,
                isSelected: false // 添加选中状态标记
            }));
        }
        console.log(hotTags.value)
        console.log(res.data)
    } catch (error) {
        ElMessage.error('加载标签失败');
    }
};

// 切换现有标签选中状态
const toggleTagSelection = (tag) => {
    // 先更新标签的选中状态
    tag.isSelected = !tag.isSelected;

    if (tag.isSelected) {
        // 如果是选中状态，则添加到已选标签列表
        selectedTags.value = [...selectedTags.value, tag];
    } else {
        // 如果是取消选中状态，则从已选标签列表中移除
        selectedTags.value = selectedTags.value.filter(t => t.tagId !== tag.tagId);
    }

    console.log("当前已选标签:", selectedTags.value);
};


// 移除已选标签
const handleSelectedRemove = (tag) => {
    if (tag.tagId) {
        // 现有标签：恢复热门标签的选中状态
        hotTags.value = hotTags.value.map(t =>
            t.tagId === tag.tagId ? { ...t, isSelected: false } : t
        );
    }
    selectedTags.value = selectedTags.value.filter(t => t !== tag);
};

// 提交标签到后端
const submitTags = async () => {
    if (selectedTags.value.length === 0) {
        ElMessage.warning('请至少选择1个标签');
        return;
    }
    try {
        // 整理标签名称为逗号分隔的字符串（如"前端技术,后端开发"）
        const tagNames = selectedTags.value.map(tag => tag.tagName).join(',');
        const res = await request.post('/api/projects/addProjectTags',{
            project_id: route.params.id,
            tags: tagNames
        });
        if (res.code === '200') {
            ElMessage.success('标签添加成功');
            data.profile.tags = tagNames // 更新标签数据
            data.profile.token = token; // 保留 token
            localStorage.setItem('code_user', JSON.stringify(data.profile));// 更新本地存储数据
            location.reload(); // 刷新页面
            dialogVisible.value = false;
        } else {
            ElMessage.error(res.msg || '标签添加失败');
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试');
    }
};
// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleDateString()
}

// 重置状态
const resetState = () => {
    selectedTags.value = [];
    hotTags.value.forEach(tag => tag.isSelected = false);
};

// 增加浏览量
const updateViews = async (views) => {
    try {
        await request.post(`/api/projects/updateViews`, views).then(res => {
            if (res.code === '200') {
                project.views = res.data.views
            }
        })
    } catch (error) {
        console.error('浏览量更新失败', error);
    }
};


// 私信跳转
const privateMessage = () => {
    router.push('/messagecenter/privatemessage/' + project.userId)
}
</script>

<style scoped>
.project-detail-container {
    position: absolute;
    top: 80px;
    width: 984px;
}

.project-header {
    margin-bottom: 15px;
    margin-left: 40px;
}

/*.stats-card {*/
/*    margin-bottom: 20px;*/
/*    margin-left: 40px;*/
/*}*/

/*.stat-item {*/
/*    border: 1px solid #ebeef5;*/
/*    border-radius: 4px;*/
/*    padding: 15px;*/
/*}*/

.file-browser {
    min-height: 400px;
}

/*作者信息区域样式*/
.content-user {
    width: 300px;
    position: fixed;
    top: 130px;
    right: 45px;
    background-color: white;
    z-index: 999;
}
</style>